package com.waves.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {

    //切入点为自定义注解
    @Pointcut("@annotation(com.waves.core.annotation.MyLog)")
    public void MyLog(){}


    @Before("MyLog()")
    public void Before(JoinPoint jp){
        System.out.println("代理对象名称："+jp.getThis().getClass().getName());
        //获取HttpServletRequest对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("==========请求信息==========");
        log.info("请求链接 : {}",request.getRequestURL().toString());
        log.info("Http Method : {}",request.getMethod());
        log.info("Class Method : {}.{}",jp.getSignature().getDeclaringTypeName(),jp.getSignature().getName());
        log.info("Ip : {}",request.getRemoteAddr());
        log.info("Args : {}", Arrays.asList(jp.getArgs()));
    }

    @Around("MyLog()")
    public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        log.info("执行时间 : {} ms", System.currentTimeMillis() - startTime);
        log.info("返回参数 : {}", result);
        return result;
    }

}
